package com.tanhua.server.service;

import com.baidu.aip.face.AipFace;
import com.tanhua.commons.properties.AliyunSmsProperties;
import com.tanhua.commons.template.AliyunOssTemplate;
import com.tanhua.commons.template.AliyunSmsTemplate;
import com.tanhua.commons.template.BaiduAipFaceTemplate;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.zookeeper.Login;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserService {
    @Reference
    private UserApi userApi;
    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private AliyunSmsTemplate smsTemplate;
    @Autowired
    private AliyunOssTemplate ossTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private BaiduAipFaceTemplate aipFaceTemplate;
    @Autowired
    private RocketMQTemplate mqTemplate;

    @Value("${tanhua.secret}")
    private String secret;


    /**
     * 手机号登录
     * @param phone
     * @return
     */
    public ResponseEntity sendVerifyCode(String phone) {

        Boolean freezingTime = redisTemplate.hasKey("FreezingTime" + phone);
        //如果还在冻结时间内，并且冻结范围是1，才禁止登录
        //如果冻结时间结束，则当前用户冻结范围也取消
        if (!freezingTime) {
            redisTemplate.delete("FreezingRange" + phone);
        } else {
            //是冻结的情况下,也就是非空，或者是类型1的情况下，不可以登录
            String number = redisTemplate.opsForValue().get("FreezingRange" + phone);
            if (number != null && "1".equals(number)) {
                return ResponseEntity.status(500).body(ErrorResult.entryInhibited());
            }
        }

//      String code = smsTemplate.sendSms(phone);
        String code = "123456";
        redisTemplate.opsForValue().set("CODE_" + phone, code, Duration.ofMinutes(5));
        log.info("发送短信验证码，mobile: {}, code: {}", phone, code);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity loginVerification(String phone, String code) {

        String value = redisTemplate.opsForValue().get("CODE_" + phone);
        if (value == null || !value.equals(code)) {
            return ResponseEntity.status(500).body(ErrorResult.smsInvalid());
        }
        redisTemplate.delete("CODE_" + phone);
        boolean isNew = false;
        User user = userApi.findByMobile(phone);
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            long id = userApi.save(user);
            user.setId(id);
            isNew = true;
        }
// 发送消息 start
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId());
        msg.put("date", new DateTime().toString("yyyy-MM-dd"));
        msg.put("type", isNew ? "0102" : "0101");
        mqTemplate.convertAndSend("tanhua-log", msg);
        log.info("【MQ消息】发送消息，topic:{}, 消息内容:{}", "tanhua-log", msg);
// 发送完毕 end


        String token = JwtUtils.createToken(user, secret);
        Map<String, Object> result = new HashMap<>();
        result.put("isNew", isNew);
        result.put("token", token);
        return ResponseEntity.ok(result);
    }

    public ResponseEntity saveUserInfo(UserInfo userInfo) {
        UserInfo user = userInfoApi.findById(userInfo.getId());
        if (user == null) {
            userInfoApi.save(userInfo);
        } else {
            userInfoApi.update(userInfo);
        }
        return ResponseEntity.ok(null);
    }

    public ResponseEntity saveAvatar(MultipartFile headPhoto, Long id) throws IOException {
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        if (!detect) {
            return ResponseEntity.status(500).body(ErrorResult.faceDetectFailed());
        }
        String path = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(path);

        userInfoApi.update(userInfo);

        return ResponseEntity.ok(null);
    }
}
